import { useState, useEffect, useCallback } from 'react'
import Taro from '@tarojs/taro'

const SEARCH_HISTORY_KEY = 'searchHistory'
const MAX_HISTORY_LENGTH = 10

export const useSearchHistory = () => {
  const [history, setHistory] = useState([])
  const [loading, setLoading] = useState(true)

  // 从本地存储加载搜索历史
  const loadHistory = useCallback(async () => {
    try {
      setLoading(true)
      const stored = await Taro.getStorageSync(SEARCH_HISTORY_KEY)
      if (stored) {
        const parsedHistory = JSON.parse(stored)
        setHistory(Array.isArray(parsedHistory) ? parsedHistory : [])
      }
    } catch (error) {
      console.error('加载搜索历史失败:', error)
      setHistory([])
    } finally {
      setLoading(false)
    }
  }, [])

  // 添加搜索历史
  const addToHistory = useCallback(async (keyword) => {
    if (!keyword || !keyword.trim()) return

    const trimmedKeyword = keyword.trim()
    const newHistory = [
      trimmedKeyword,
      ...history.filter(h => h !== trimmedKeyword)
    ].slice(0, MAX_HISTORY_LENGTH)

    setHistory(newHistory)

    try {
      await Taro.setStorageSync(SEARCH_HISTORY_KEY, JSON.stringify(newHistory))
    } catch (error) {
      console.error('保存搜索历史失败:', error)
    }
  }, [history])

  // 清除单个搜索历史
  const removeFromHistory = useCallback(async (keyword) => {
    const newHistory = history.filter(h => h !== keyword)
    setHistory(newHistory)

    try {
      await Taro.setStorageSync(SEARCH_HISTORY_KEY, JSON.stringify(newHistory))
    } catch (error) {
      console.error('删除搜索历史失败:', error)
    }
  }, [history])

  // 清除所有搜索历史
  const clearHistory = useCallback(async () => {
    setHistory([])
    try {
      await Taro.removeStorageSync(SEARCH_HISTORY_KEY)
    } catch (error) {
      console.error('清除搜索历史失败:', error)
    }
  }, [])

  // 获取热门搜索词
  const getHotSearchWords = useCallback(() => {
    return [
      '玻尿酸',
      '瘦脸针',
      '双眼皮',
      '隆鼻',
      '美白针',
      '祛痘',
      '抗衰',
      '隆胸',
      '吸脂',
      '植发'
    ]
  }, [])

  // 获取搜索建议
  const getSearchSuggestions = useCallback((keyword) => {
    if (!keyword || !keyword.trim()) return []

    const hotWords = getHotSearchWords()
    const suggestions = []

    // 从热门搜索词中匹配
    hotWords.forEach(word => {
      if (word.includes(keyword) || keyword.includes(word)) {
        suggestions.push(word)
      }
    })

    // 从历史记录中匹配
    history.forEach(item => {
      if (item.includes(keyword) && !suggestions.includes(item)) {
        suggestions.push(item)
      }
    })

    return suggestions.slice(0, 8) // 最多显示8个建议
  }, [history, getHotSearchWords])

  useEffect(() => {
    loadHistory()
  }, [loadHistory])

  return {
    history,
    loading,
    addToHistory,
    removeFromHistory,
    clearHistory,
    getHotSearchWords,
    getSearchSuggestions
  }
}

export default useSearchHistory
